using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MultiplayerServerDiscoveryHandlers
{
	public class FindServersHandler : MessageHandler
	{
		private Coroutine discoveryMessageSender;

		private float delayBetweenMessagesSeconds = 0.5f;

		public List<Server> servers = new List<Server>();

		public override bool CanAcceptMessage(UDPMessageBase message)
		{
			return (message.type == UDPMessageBase.MessageType.ServerIntroductionMessage || message.type == UDPMessageBase.MessageType.ServerReject) && base.CanAcceptMessage(message);
		}

		public override void OnMessageReceived(UDPMessageBase message)
		{
			if (message.type == UDPMessageBase.MessageType.ServerReject)
			{
				servers.RemoveByEndpoint(message.senderAddress, message.senderPort);
			}
			else if (message.type == UDPMessageBase.MessageType.ServerIntroductionMessage && !servers.ContainsEndpoint(message.senderAddress, message.senderPort))
			{
				servers.Add(new Server(message.senderAddress, message.senderPort));
			}
		}

		public override void OnAddedToServer(GGUDPNetworkServer server)
		{
			base.OnAddedToServer(server);
			discoveryMessageSender = server.StartCoroutine(SendDiscoveryMessagesEvery(delayBetweenMessagesSeconds));
		}

		public override void OnRemovedFromServer(GGUDPNetworkServer server)
		{
			base.OnRemovedFromServer(server);
			server.StopCoroutine(discoveryMessageSender);
		}

		private IEnumerator SendDiscoveryMessagesEvery(float delayBetweenMessageSeconds)
		{
			while (true)
			{
				server.SendBroadcast(new DiscoveryMessage().SerializeToBytes());
				yield return new WaitForSeconds(delayBetweenMessagesSeconds);
			}
		}
	}
}
